/**
 * 对话历史存储服务
 */

export interface ChatMessage {
    id: string;
    timestamp: number;
    type: 'user' | 'ai';
    content: string;
    voiceCharacter?: string; // 使用的语音角色
}

export interface ChatSession {
    id: string;
    startTime: number;
    endTime?: number;
    messages: ChatMessage[];
    voiceCharacter?: string; // 会话使用的语音角色
}

class ChatHistoryService {
    private storageKey = 'chat_history';
    private maxSessions = 50; // 最大存储会话数
    private currentSession: ChatSession | null = null;

    // 开始新会话
    startNewSession(voiceCharacter?: string): string {
        const sessionId = `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
        this.currentSession = {
            id: sessionId,
            startTime: Date.now(),
            messages: [],
            voiceCharacter
        };
        console.log('📝 开始新对话会话:', sessionId);
        return sessionId;
    }

    // 添加用户消息
    addUserMessage(content: string): void {
        if (!this.currentSession) {
            this.startNewSession();
        }

        const message: ChatMessage = {
            id: `user_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
            timestamp: Date.now(),
            type: 'user',
            content: content.trim()
        };

        this.currentSession!.messages.push(message);
        console.log('📝 添加用户消息:', message);
    }

    // 添加AI回复
    addAiMessage(content: string, voiceCharacter?: string): void {
        if (!this.currentSession) {
            this.startNewSession();
        }

        const message: ChatMessage = {
            id: `ai_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
            timestamp: Date.now(),
            type: 'ai',
            content: content.trim(),
            voiceCharacter
        };

        this.currentSession!.messages.push(message);
        console.log('📝 添加AI回复:', message);
    }

    // 结束当前会话
    endCurrentSession(): void {
        if (this.currentSession) {
            this.currentSession.endTime = Date.now();
            this.saveSession(this.currentSession);
            console.log('📝 结束对话会话:', this.currentSession.id);
            this.currentSession = null;
        }
    }

    // 保存会话到本地存储
    private saveSession(session: ChatSession): void {
        try {
            const sessions = this.getAllSessions();
            sessions.push(session);

            // 按开始时间排序
            sessions.sort((a, b) => b.startTime - a.startTime);

            // 限制存储数量
            if (sessions.length > this.maxSessions) {
                sessions.splice(this.maxSessions);
            }

            localStorage.setItem(this.storageKey, JSON.stringify(sessions));
            console.log('📝 会话已保存:', session.id);
        } catch (error) {
            console.error('保存会话失败:', error);
        }
    }

    // 获取所有会话
    getAllSessions(): ChatSession[] {
        try {
            const stored = localStorage.getItem(this.storageKey);
            return stored ? JSON.parse(stored) : [];
        } catch (error) {
            console.error('获取会话失败:', error);
            return [];
        }
    }

    // 获取当前会话
    getCurrentSession(): ChatSession | null {
        return this.currentSession;
    }

    // 获取所有消息（包括当前会话）
    getAllMessages(): ChatMessage[] {
        const sessions = this.getAllSessions();
        const allMessages: ChatMessage[] = [];

        // 添加历史会话的消息
        sessions.forEach(session => {
            allMessages.push(...session.messages);
        });

        // 添加当前会话的消息
        if (this.currentSession) {
            allMessages.push(...this.currentSession.messages);
        }

        // 按时间排序
        allMessages.sort((a, b) => a.timestamp - b.timestamp);
        return allMessages;
    }

    // 清除所有历史记录
    clearAllHistory(): void {
        localStorage.removeItem(this.storageKey);
        this.currentSession = null;
        console.log('📝 已清除所有对话历史');
    }

    // 导出对话历史为文本格式
    exportAsText(): string {
        const messages = this.getAllMessages();
        const sessions = this.getAllSessions();

        let exportText = `# 对话历史导出\n`;
        exportText += `导出时间: ${new Date().toLocaleString()}\n`;
        exportText += `总消息数: ${messages.length}\n`;
        exportText += `总会话数: ${sessions.length}\n\n`;

        // 按会话分组导出
        sessions.forEach((session, sessionIndex) => {
            exportText += `## 会话 ${sessionIndex + 1}\n`;
            exportText += `会话ID: ${session.id}\n`;
            exportText += `开始时间: ${new Date(session.startTime).toLocaleString()}\n`;
            if (session.endTime) {
                exportText += `结束时间: ${new Date(session.endTime).toLocaleString()}\n`;
            }
            if (session.voiceCharacter) {
                exportText += `语音角色: ${session.voiceCharacter}\n`;
            }
            exportText += `消息数: ${session.messages.length}\n\n`;

            // 导出会话内的消息
            session.messages.forEach((message, messageIndex) => {
                const timeStr = new Date(message.timestamp).toLocaleString();
                const speaker = message.type === 'user' ? '👤 用户' : '🤖 AI';
                exportText += `${messageIndex + 1}. [${timeStr}] ${speaker}:\n`;
                exportText += `${message.content}\n\n`;
            });

            exportText += `---\n\n`;
        });

        // 如果有当前会话，也导出
        if (this.currentSession && this.currentSession.messages.length > 0) {
            exportText += `## 当前会话\n`;
            exportText += `会话ID: ${this.currentSession.id}\n`;
            exportText += `开始时间: ${new Date(this.currentSession.startTime).toLocaleString()}\n`;
            if (this.currentSession.voiceCharacter) {
                exportText += `语音角色: ${this.currentSession.voiceCharacter}\n`;
            }
            exportText += `消息数: ${this.currentSession.messages.length}\n\n`;

            this.currentSession.messages.forEach((message, messageIndex) => {
                const timeStr = new Date(message.timestamp).toLocaleString();
                const speaker = message.type === 'user' ? '👤 用户' : '🤖 AI';
                exportText += `${messageIndex + 1}. [${timeStr}] ${speaker}:\n`;
                exportText += `${message.content}\n\n`;
            });
        }

        return exportText;
    }

    // 导出对话历史为JSON格式
    exportAsJson(): string {
        const sessions = this.getAllSessions();
        const currentSession = this.currentSession;

        const exportData = {
            exportTime: new Date().toISOString(),
            totalMessages: this.getAllMessages().length,
            totalSessions: sessions.length,
            sessions: sessions,
            currentSession: currentSession
        };

        return JSON.stringify(exportData, null, 2);
    }
}

export const chatHistoryService = new ChatHistoryService();
